<template>
	<view class="JSwiperGrid">
		<swiper circular :indicator-dots="false" class="j-swiper" @change="swiperChange" :style="swiperStyle" ref="swiperRef" :current="currentIndex">
			<swiper-item v-for="(item, i) in swiperList" :key="i">
				<JGrid ref="jGridRef" :list="item"></JGrid>
			</swiper-item>
		</swiper>

		<view class="j-swiper-dots" v-if="swiperList.length > 1">
			<view v-for="(item, index) in swiperList" :key="index" class="j-swiper-dot" :class="{ 'j-swiper-dot-active': currentIndex === index }" @click="goToSlide(index)"></view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'JSwiperGrid',
	props: {
		list: {
			type: Array,
			default: () => []
		},
		count: {
			type: Number,
			default: 10
		},
		height: {
			type: Number,
			default: 330
		}
	},
	computed: {
		swiperList() {
			return this.splitList(this.list);
		},
		swiperStyle() {
			return {
				height: `${this.dynamicHeight || this.height}rpx`
			};
		}
	},
	methods: {
		swiperChange(event) {
			this.currentIndex = event.detail.current;
			console.log(event.detail, '--------------event.detail ');
		},
		goToSlide(index) {
			// 通过修改currentIndex来切换swiper
			this.currentIndex = index;
		},
		splitList(data) {
			let result = [];
			let count = this.count;
			for (let i = 0; i < data.length; i += count) {
				result.push(data.slice(i, i + count));
			}
			return result;
		},
		getGridHeight() {
			// 使用 uni.createSelectorQuery 获取组件高度
			const query = uni.createSelectorQuery().in(this);
			query
				.select('.JGrid')
				.boundingClientRect((rect) => {
					if (rect && rect.height) {
						// 将px转换为rpx
						const systemInfo = uni.getSystemInfoSync();
						const rpxRatio = 750 / systemInfo.windowWidth;
						this.dynamicHeight = Math.ceil(rect.height * rpxRatio);
						console.log('获取到的JGrid高度:', this.dynamicHeight + 'rpx');
					}
				})
				.exec();
		}
	},
	created() {},
	mounted() {
		this.$nextTick(() => {
			this.getGridHeight();
		});
	},
	data() {
		return {
			dynamicHeight: null,
			currentIndex: 0
		};
	},
	watch: {
		list: {
			handler() {
				this.$nextTick(() => {
					this.getGridHeight();
				});
			},
			deep: true
		}
	}
};
</script>

<style lang="less">
.JSwiperGrid {
	position: relative;
	width: 100%;
	padding: @page-col-spacing @page-row-spacing;
	background: #fff;
	.j-swiper {
		width: 100%;
	}
	.j-swiper-dots {
		position: absolute;
		bottom: 10rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		.j-swiper-dot {
			width: 26rpx;
			height: 4rpx;
			background: #ccc;
			margin: 0 10rpx;
			&.j-swiper-dot-active {
				background: #007aff;
			}
		}
	}
}
</style>
